<template>
  <div class="solar-dashboard">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="logo">
        <h1>行星观测站</h1>
        <p v-if="currentUser">欢迎，{{ currentUser.username }}</p>
      </div>
      <div class="user-controls">
        <button class="btn btn-secondary" @click="saveView">保存视图</button>
        <button class="btn btn-primary" @click="exportData">导出数据</button>
        <button class="btn btn-danger" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <!-- 主内容区 -->
    <div class="dashboard-content">
      <!-- 太阳系视图 -->
      <div class="planet-system-container" ref="containerRef">
        <!-- 详细控制面板 -->
        <div class="advanced-controls">
          <div class="control-panel">
            <h3>时间控制</h3>
            <div class="control-group">
              <label>时间速度:</label>
              <input 
                type="range" 
                v-model.number="timeSpeed" 
                min="0.1" 
                max="50" 
                step="0.1"
              />
              <span>{{ timeSpeed.toFixed(1) }}x</span>
            </div>
            <div class="control-group">
              <button @click="pauseSimulation" class="btn">暂停</button>
              <button @click="resumeSimulation" class="btn">继续</button>
              <button @click="resetTime" class="btn">重置时间</button>
            </div>
          </div>

          <div class="control-panel">
            <h3>视觉设置</h3>
            <div class="control-group">
              <label><input type="checkbox" v-model="showOrbits" /> 显示轨道</label>
            </div>
            <div class="control-group">
              <label><input type="checkbox" v-model="showLabels" /> 显示标签</label>
            </div>
            <div class="control-group">
              <label><input type="checkbox" v-model="showMoons" /> 显示卫星</label>
            </div>
            <div class="control-group">
              <label><input type="checkbox" v-model="realScale" /> 真实比例</label>
            </div>
            <div class="control-group">
              <label><input type="checkbox" v-model="showRings" /> 显示光环</label>
            </div>
          </div>

          <div class="control-panel">
            <h3>导航控制</h3>
            <div class="control-group">
              <select v-model="targetObject" @change="focusObject">
                <option value="sun">太阳</option>
                <option value="mercury">水星</option>
                <option value="venus">金星</option>
                <option value="earth">地球</option>
                <option value="moon">月球</option>
                <option value="mars">火星</option>
                <option value="jupiter">木星</option>
                <option value="io">木卫一</option>
                <option value="europa">木卫二</option>
                <option value="ganymede">木卫三</option>
                <option value="callisto">木卫四</option>
                <option value="saturn">土星</option>
                <option value="uranus">天王星</option>
                <option value="neptune">海王星</option>
              </select>
            </div>
            <div class="control-group">
              <button @click="zoomIn" class="btn">放大</button>
              <button @click="zoomOut" class="btn">缩小</button>
              <button @click="resetView" class="btn">重置视图</button>
            </div>
          </div>

          <div class="control-panel">
            <h3>卫星系统</h3>
            <div class="control-group">
              <label><input type="checkbox" v-model="showDetailedMoons" /> 详细卫星模型</label>
            </div>
            <div class="control-group">
              <label><input type="checkbox" v-model="showMoonOrbits" /> 显示卫星轨道</label>
            </div>
            <div class="moon-info" v-if="selectedMoon">
              <h4>{{ selectedMoon.name }}</h4>
              <p>轨道半径: {{ selectedMoon.distance }}km</p>
              <p>公转周期: {{ selectedMoon.period }}天</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 信息面板 -->
      <div class="info-panel" v-if="selectedObject">
        <h3>{{ selectedObject.name }}</h3>
        <div class="info-content">
          <div class="info-item">
            <span class="label">类型:</span>
            <span class="value">{{ selectedObject.type }}</span>
          </div>
          <div class="info-item">
            <span class="label">直径:</span>
            <span class="value">{{ selectedObject.diameter }}km</span>
          </div>
          <div class="info-item">
            <span class="label">距离:</span>
            <span class="value">{{ selectedObject.distance }}天文单位</span>
          </div>
          <div class="info-item">
            <span class="label">公转周期:</span>
            <span class="value">{{ selectedObject.orbitPeriod }}天</span>
          </div>
          <div class="info-item">
            <span class="label">自转周期:</span>
            <span class="value">{{ selectedObject.rotationPeriod }}小时</span>
          </div>
          <div class="info-item" v-if="selectedObject.moonsCount > 0">
            <span class="label">卫星数量:</span>
            <span class="value">{{ selectedObject.moonsCount }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, inject } from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { Text } from 'troika-three-text'

export default {
  name: 'SolarSystemDashboard',
  emits: ['logout'],
  setup(props, { emit }) {
    // 注入当前用户信息
    const currentUser = inject('currentUser', { username: '观测者' })
    
    // 容器引用
    const containerRef = ref(null)
    
    // Three.js 相关对象
    let scene = null
    let camera = null
    let renderer = null
    let controls = null
    let animationId = null
    let clock = null
    
    // 状态变量
    const timeSpeed = ref(1.0)
    const showOrbits = ref(true)
    const showLabels = ref(true)
    const showMoons = ref(true)
    const realScale = ref(false)
    const showRings = ref(true)
    const showDetailedMoons = ref(true)
    const showMoonOrbits = ref(true)
    const targetObject = ref('sun')
    const selectedObject = ref(null)
    const selectedMoon = ref(null)
    const isPaused = ref(false)
    
    // 存储场景对象的引用
    const objects = {
      sun: null,
      planets: {},
      moons: {},
      orbits: {},
      labels: {}
    }
    
    // 增强的行星和卫星数据
    const planetaryData = {
      sun: {
        name: '太阳',
        type: '恒星',
        diameter: 1392700,
        distance: 0,
        color: 0xffff00,
        rotationPeriod: 25.4,
        orbitPeriod: 0,
        moonsCount: 0
      },
      mercury: {
        name: '水星',
        type: '行星',
        diameter: 4879,
        distance: 0.39,
        color: 0xaaaaaa,
        orbitSpeed: 47.4,
        rotationSpeed: 1407.6,
        yearLength: 87.97,
        dayLength: 1407.6,
        orbitPeriod: 87.97,
        rotationPeriod: 1407.6,
        moonsCount: 0
      },
      venus: {
        name: '金星',
        type: '行星',
        diameter: 12104,
        distance: 0.72,
        color: 0xe3a95c,
        orbitSpeed: 35.0,
        rotationSpeed: 2802.0,
        yearLength: 224.7,
        dayLength: 2802.0,
        orbitPeriod: 224.7,
        rotationPeriod: 2802.0,
        moonsCount: 0
      },
      earth: {
        name: '地球',
        type: '行星',
        diameter: 12756,
        distance: 1.0,
        color: 0x2233ff,
        orbitSpeed: 29.8,
        rotationSpeed: 23.93,
        yearLength: 365.26,
        dayLength: 23.93,
        orbitPeriod: 365.26,
        rotationPeriod: 23.93,
        moonsCount: 1,
        moons: [
          {
            id: 'moon',
            name: '月球',
            distance: 384400,
            radius: 1737,
            diameter: 3474,
            color: 0xaaaaaa,
            orbitSpeed: 1.022,
            rotationSpeed: 27.32,
            period: 27.32
          }
        ]
      },
      mars: {
        name: '火星',
        type: '行星',
        diameter: 6792,
        distance: 1.52,
        color: 0xff3300,
        orbitSpeed: 24.1,
        rotationSpeed: 24.6,
        yearLength: 686.98,
        dayLength: 24.6,
        orbitPeriod: 686.98,
        rotationPeriod: 24.6,
        moonsCount: 2,
        moons: [
          {
            id: 'phobos',
            name: '火卫一',
            distance: 9376,
            radius: 11,
            diameter: 22,
            color: 0x888888,
            orbitSpeed: 0.31,
            period: 0.31
          },
          {
            id: 'deimos',
            name: '火卫二',
            distance: 23459,
            radius: 6,
            diameter: 12,
            color: 0x666666,
            orbitSpeed: 0.12,
            period: 1.26
          }
        ]
      },
      jupiter: {
        name: '木星',
        type: '行星',
        diameter: 142984,
        distance: 5.2,
        color: 0xffaa88,
        orbitSpeed: 13.1,
        rotationSpeed: 9.9,
        yearLength: 4332.59,
        dayLength: 9.9,
        hasRings: true,
        orbitPeriod: 4332.59,
        rotationPeriod: 9.9,
        moonsCount: 79,
        moons: [
          {
            id: 'io',
            name: '木卫一',
            distance: 421700,
            radius: 1821,
            diameter: 3642,
            color: 0xff8888,
            orbitSpeed: 42.8,
            period: 1.77
          },
          {
            id: 'europa',
            name: '木卫二',
            distance: 671034,
            radius: 1569,
            diameter: 3138,
            color: 0x88aaff,
            orbitSpeed: 35.5,
            period: 3.55
          },
          {
            id: 'ganymede',
            name: '木卫三',
            distance: 1070412,
            radius: 2634,
            diameter: 5268,
            color: 0xaaaaaa,
            orbitSpeed: 26.5,
            period: 7.15
          },
          {
            id: 'callisto',
            name: '木卫四',
            distance: 1882709,
            radius: 2410,
            diameter: 4820,
            color: 0x999999,
            orbitSpeed: 18.1,
            period: 16.69
          }
        ]
      },
      saturn: {
        name: '土星',
        type: '行星',
        diameter: 120536,
        distance: 9.58,
        color: 0xffcc66,
        orbitSpeed: 9.7,
        rotationSpeed: 10.7,
        yearLength: 10759.2,
        dayLength: 10.7,
        hasRings: true,
        ringColor: 0xffddaa,
        orbitPeriod: 10759.2,
        rotationPeriod: 10.7,
        moonsCount: 82,
        moons: [
          {
            id: 'titan',
            name: '土卫六',
            distance: 1221870,
            radius: 2575,
            diameter: 5150,
            color: 0x886644,
            orbitSpeed: 9.6,
            period: 15.95
          }
        ]
      },
      uranus: {
        name: '天王星',
        type: '行星',
        diameter: 51118,
        distance: 19.2,
        color: 0x99ccff,
        orbitSpeed: 6.8,
        rotationSpeed: 17.2,
        yearLength: 30688.5,
        dayLength: 17.2,
        hasRings: true,
        ringColor: 0x777799,
        orbitPeriod: 30688.5,
        rotationPeriod: 17.2,
        moonsCount: 27,
        moons: [
          {
            id: 'titania',
            name: '天卫三',
            distance: 436300,
            radius: 788,
            diameter: 1576,
            color: 0x9999aa,
            orbitSpeed: 6.8,
            period: 8.71
          }
        ]
      },
      neptune: {
        name: '海王星',
        type: '行星',
        diameter: 49528,
        distance: 30.05,
        color: 0x3366ff,
        orbitSpeed: 5.4,
        rotationSpeed: 16.1,
        yearLength: 60195,
        dayLength: 16.1,
        hasRings: true,
        ringColor: 0x223366,
        orbitPeriod: 60195,
        rotationPeriod: 16.1,
        moonsCount: 14,
        moons: [
          {
            id: 'triton',
            name: '海卫一',
            distance: 354759,
            radius: 1353,
            diameter: 2706,
            color: 0x555577,
            orbitSpeed: 4.4,
            period: 5.88
          }
        ]
      }
    }
    
    // 初始化场景
    const initScene = () => {
      if (!containerRef.value) return
      
      // 创建场景
      scene = new THREE.Scene()
      scene.background = new THREE.Color(0x000011)
      
      // 添加星空背景
      createStarfield()
      
      // 创建相机
      camera = new THREE.PerspectiveCamera(
        75, 
        containerRef.value.clientWidth / containerRef.value.clientHeight,
        0.1, 
        100000
      )
      camera.position.set(500, 300, 500)
      
      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ antialias: true })
      renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight)
      renderer.setPixelRatio(window.devicePixelRatio)
      containerRef.value.appendChild(renderer.domElement)
      
      // 添加高级轨道控制器
      controls = new OrbitControls(camera, renderer.domElement)
      controls.enableDamping = true
      controls.dampingFactor = 0.05
      controls.autoRotate = false
      controls.enablePan = true
      controls.panSpeed = 0.5
      controls.zoomSpeed = 1.0
      controls.rotateSpeed = 1.0
      controls.screenSpacePanning = false
      
      // 添加环境光
      const ambientLight = new THREE.AmbientLight(0x050505)
      scene.add(ambientLight)
      
      // 创建时钟
      clock = new THREE.Clock()
      
      // 创建太阳系
      createSun()
      createPlanets()
      
      // 添加鼠标交互
      addMouseInteraction()
      
      // 开始动画
      animate()
      
      // 监听窗口大小变化
      window.addEventListener('resize', handleResize)
    }
    
    // 创建星空背景
    const createStarfield = () => {
      const starGeometry = new THREE.BufferGeometry()
      const starCount = 5000
      const positions = new Float32Array(starCount * 3)
      const colors = new Float32Array(starCount * 3)
      
      for (let i = 0; i < starCount; i++) {
        const i3 = i * 3
        positions[i3] = (Math.random() - 0.5) * 20000
        positions[i3 + 1] = (Math.random() - 0.5) * 20000
        positions[i3 + 2] = (Math.random() - 0.5) * 20000
        
        // 随机颜色
        const brightness = Math.random()
        colors[i3] = brightness
        colors[i3 + 1] = brightness
        colors[i3 + 2] = brightness
      }
      
      starGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
      starGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
      
      const starMaterial = new THREE.PointsMaterial({
        size: 2,
        vertexColors: true,
        transparent: true,
        opacity: 0.8
      })
      
      const starfield = new THREE.Points(starGeometry, starMaterial)
      scene.add(starfield)
    }
    
    // 创建太阳
    const createSun = () => {
      // 太阳半径（非真实比例，为了可视化）
      const radius = realScale.value ? 696340 / 1000 : 20
      
      // 创建太阳材质
      const sunMaterial = new THREE.MeshBasicMaterial({ 
        color: planetaryData.sun.color,
        emissive: planetaryData.sun.color,
        emissiveIntensity: 1
      })
      
      // 创建太阳几何体
      const sunGeometry = new THREE.SphereGeometry(radius, 64, 64)
      
      // 创建太阳网格
      const sun = new THREE.Mesh(sunGeometry, sunMaterial)
      scene.add(sun)
      
      // 创建太阳发光效果
      const sunLight = new THREE.PointLight(planetaryData.sun.color, 2, 10000)
      sun.add(sunLight)
      
      // 存储太阳引用
      objects.sun = sun
      
      // 创建太阳标签
      createLabel(planetaryData.sun.name, sun, planetaryData.sun.color)
    }
    
    // 创建行星
    const createPlanets = () => {
      Object.entries(planetaryData).forEach(([key, data]) => {
        if (key === 'sun') return // 太阳已单独创建
        
        // 创建行星轨道
        if (showOrbits.value) {
          createOrbit(data.distance * 100)
        }
        
        // 创建行星父对象（用于轨道运动）
        const orbitGroup = new THREE.Object3D()
        scene.add(orbitGroup)
        
        // 创建行星父对象（用于自转轴倾斜）
        const planetGroup = new THREE.Object3D()
        
        // 模拟行星自转轴倾斜
        if (key === 'earth') planetGroup.rotation.x = 0.4091
        if (key === 'saturn') planetGroup.rotation.x = 0.466
        if (key === 'uranus') planetGroup.rotation.x = 1.77
        if (key === 'neptune') planetGroup.rotation.x = 0.77
        
        orbitGroup.add(planetGroup)
        
        // 计算行星半径
        const radius = realScale.value ? data.diameter / 10000 : Math.max(1, data.diameter / 4000)
        
        // 创建行星几何体
        const planetGeometry = new THREE.SphereGeometry(radius, 32, 32)
        
        // 创建行星材质
        const planetMaterial = new THREE.MeshPhongMaterial({ 
          color: data.color,
          shininess: 10
        })
        
        // 创建行星网格
        const planet = new THREE.Mesh(planetGeometry, planetMaterial)
        planet.position.set(data.distance * 100, 0, 0)
        planetGroup.add(planet)
        
        // 存储行星信息
        planet.planetData = data
        
        // 添加光环（土星、木星、天王星、海王星）
        if (data.hasRings && showRings.value) {
          const ringRadius = radius * 1.5
          const ringGeometry = new THREE.RingGeometry(ringRadius, ringRadius * 1.8, 64)
          const ringMaterial = new THREE.MeshBasicMaterial({ 
            color: data.ringColor || 0xaaaaaa, 
            side: THREE.DoubleSide,
            transparent: true,
            opacity: 0.6
          })
          
          const ring = new THREE.Mesh(ringGeometry, ringMaterial)
          ring.rotation.x = Math.PI / 2
          planetGroup.add(ring)
          ring.position.set(data.distance * 100, 0, 0)
        }
        
        // 创建卫星
        if (data.moons && data.moons.length > 0 && showMoons.value) {
          data.moons.forEach(moon => {
            const moonObj = createMoon(planet, moon, radius)
            objects.moons[moon.id] = moonObj
          })
        }
        
        // 存储行星引用
        objects.planets[key] = {
          mesh: planet,
          orbitGroup: orbitGroup,
          planetGroup: planetGroup,
          data: data,
          orbitAngle: Math.random() * Math.PI * 2 // 随机初始轨道角度
        }
        
        // 创建行星标签
        createLabel(data.name, planet, data.color)
      })
    }
    
    // 创建卫星
    const createMoon = (planet, moonData, planetRadius) => {
      // 创建卫星轨道
      const moonOrbitGroup = new THREE.Object3D()
      planet.add(moonOrbitGroup)
      
      // 卫星轨道距离（基于行星大小）
      const orbitDistance = planetRadius * 1.5 + (moonData.distance / 100000)
      
      // 创建卫星轨道环
      if (showMoonOrbits.value) {
        const moonOrbitGeometry = new THREE.RingGeometry(orbitDistance, orbitDistance + 0.05, 64)
        const moonOrbitMaterial = new THREE.MeshBasicMaterial({
          color: 0x444444,
          side: THREE.DoubleSide,
          transparent: true,
          opacity: 0.3
        })
        const moonOrbit = new THREE.Mesh(moonOrbitGeometry, moonOrbitMaterial)
        moonOrbit.rotation.x = Math.PI / 2
        moonOrbitGroup.add(moonOrbit)
      }
      
      // 卫星大小
      const moonRadius = Math.max(0.1, moonData.diameter / 4000)
      
      // 创建卫星几何体和材质
      const moonGeometry = new THREE.SphereGeometry(moonRadius, 16, 16)
      const moonMaterial = new THREE.MeshPhongMaterial({ 
        color: moonData.color,
        shininess: 5
      })
      
      // 创建卫星网格
      const moon = new THREE.Mesh(moonGeometry, moonMaterial)
      moon.position.set(orbitDistance, 0, 0)
      moonOrbitGroup.add(moon)
      
      // 存储卫星信息
      moon.moonData = moonData
      
      // 存储卫星轨道数据
      moon.orbitGroup = moonOrbitGroup
      moon.orbitAngle = Math.random() * Math.PI * 2
      moon.orbitSpeed = moonData.orbitSpeed
      
      // 创建卫星标签
      createLabel(moonData.name, moon, moonData.color, 1.2)
      
      return moon
    }
    
    // 创建轨道
    const createOrbit = (radius) => {
      const orbitGeometry = new THREE.RingGeometry(radius, radius + 0.1, 128)
      const orbitMaterial = new THREE.MeshBasicMaterial({ 
        color: 0x333333,
        side: THREE.DoubleSide,
        transparent: true,
        opacity: 0.5
      })
      
      const orbit = new THREE.Mesh(orbitGeometry, orbitMaterial)
      orbit.rotation.x = Math.PI / 2
      scene.add(orbit)
      
      return orbit
    }
    
    // 创建标签
    const createLabel = (name, object, color, fontSize = 2) => {
      const text = new Text()
      text.text = name
      text.fontSize = fontSize
      text.color = color
      text.anchorX = 'center'
      text.anchorY = 'bottom'
      text.textAlign = 'center'
      text.outlineWidth = 0.1
      text.outlineColor = 0x000000
      text.sync()
      
      // 将标签添加到对象附近，但稍高一点
      const labelGroup = new THREE.Object3D()
      const offset = object.geometry ? object.geometry.parameters.radius + 2 : 2
      labelGroup.position.set(0, offset, 0)
      labelGroup.add(text)
      
      object.add(labelGroup)
      
      // 初始隐藏标签
      labelGroup.visible = showLabels.value
      
      // 存储标签引用
      objects.labels[name] = labelGroup
      
      return labelGroup
    }
    
    // 添加鼠标交互
    const addMouseInteraction = () => {
      const raycaster = new THREE.Raycaster()
      const mouse = new THREE.Vector2()
      
      const handleMouseClick = (event) => {
        // 计算鼠标在归一化设备坐标中的位置
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
        
        // 设置射线投射器
        raycaster.setFromCamera(mouse, camera)
        
        // 收集所有可点击对象
        const clickableObjects = []
        if (objects.sun) clickableObjects.push(objects.sun)
        Object.values(objects.planets).forEach(planet => clickableObjects.push(planet.mesh))
        Object.values(objects.moons).forEach(moon => clickableObjects.push(moon))
        
        // 执行射线投射
        const intersects = raycaster.intersectObjects(clickableObjects)
        
        if (intersects.length > 0) {
          const clickedObject = intersects[0].object
          
          // 处理点击的对象
          if (clickedObject === objects.sun) {
            selectedObject.value = planetaryData.sun
            selectedMoon.value = null
            targetObject.value = 'sun'
          } else if (clickedObject.planetData) {
            selectedObject.value = clickedObject.planetData
            selectedMoon.value = null
            Object.entries(planetaryData).forEach(([key, data]) => {
              if (data.name === clickedObject.planetData.name) {
                targetObject.value = key
              }
            })
          } else if (clickedObject.moonData) {
            selectedMoon.value = clickedObject.moonData
            // 找到父行星
            const parentPlanet = clickedObject.parent.parent // moon -> orbitGroup -> planet
            if (parentPlanet && parentPlanet.planetData) {
              selectedObject.value = parentPlanet.planetData
            }
            targetObject.value = clickedObject.moonData.id
          }
          
          // 聚焦到点击的对象
          focusObject()
        }
      }
      
      window.addEventListener('click', handleMouseClick)
    }
    
    // 聚焦到特定对象
    const focusObject = () => {
      if (!controls) return
      
      if (targetObject.value === 'sun') {
        controls.target.set(0, 0, 0)
        camera.position.set(500, 300, 500)
      } else if (objects.planets[targetObject.value]) {
        const planet = objects.planets[targetObject.value]
        const distance = planet.data.distance * 100 * 2
        controls.target.copy(planet.mesh.position)
        camera.position.set(distance, distance / 2, distance)
        selectedObject.value = planet.data
        selectedMoon.value = null
      } else if (objects.moons[targetObject.value]) {
        const moon = objects.moons[targetObject.value]
        const parentPlanet = moon.parent.parent // moon -> orbitGroup -> planet
        
        if (parentPlanet) {
          // 获取世界坐标
          const worldPosition = new THREE.Vector3()
          moon.getWorldPosition(worldPosition)
          
          // 设置目标和相机位置
          controls.target.copy(worldPosition)
          camera.position.set(worldPosition.x + 20, worldPosition.y + 10, worldPosition.z + 20)
          
          // 更新选择信息
          selectedMoon.value = moon.moonData
          if (parentPlanet.planetData) {
            selectedObject.value = parentPlanet.planetData
          }
        }
      }
      
      controls.update()
    }
    
    // 动画循环
    const animate = () => {
      animationId = requestAnimationFrame(animate)
      
      if (!isPaused.value) {
        const delta = clock.getDelta() * timeSpeed.value
        
        // 更新行星运动
        Object.values(objects.planets).forEach(planet => {
          // 轨道运动（公转）
          const orbitSpeed = (2 * Math.PI) / (planet.data.yearLength / 365.26) * delta
          planet.orbitAngle += orbitSpeed
          planet.orbitGroup.rotation.y = planet.orbitAngle
          
          // 自转
          const rotationSpeed = (2 * Math.PI) / (24 / planet.data.dayLength) * delta
          planet.planetGroup.rotation.y += rotationSpeed
          
          // 更新卫星运动
          if (showMoons.value) {
            planet.mesh.children.forEach(child => {
              if (child.orbitGroup) {
                // 卫星轨道运动
                child.orbitAngle += (2 * Math.PI) * (child.orbitSpeed / 24) * delta
                child.orbitGroup.rotation.y = child.orbitAngle
              }
            })
          }
        })
      }
      
      // 更新控制器
      if (controls) {
        controls.update()
      }
      
      // 渲染场景
      renderer.render(scene, camera)
    }
    
    // 控制方法
    const pauseSimulation = () => {
      isPaused.value = true
    }
    
    const resumeSimulation = () => {
      isPaused.value = false
    }
    
    const resetTime = () => {
      // 重置所有轨道角度
      Object.values(objects.planets).forEach(planet => {
        planet.orbitAngle = Math.random() * Math.PI * 2
      })
      Object.values(objects.moons).forEach(moon => {
        if (moon.orbitAngle !== undefined) {
          moon.orbitAngle = Math.random() * Math.PI * 2
        }
      })
    }
    
    const zoomIn = () => {
      camera.position.multiplyScalar(0.8)
    }
    
    const zoomOut = () => {
      camera.position.multiplyScalar(1.2)
    }
    
    const resetView = () => {
      controls.target.set(0, 0, 0)
      camera.position.set(500, 300, 500)
      controls.update()
    }
    
    // 处理窗口大小变化
    const handleResize = () => {
      if (!containerRef.value || !camera || !renderer) return
      
      const { clientWidth, clientHeight } = containerRef.value
      
      camera.aspect = clientWidth / clientHeight
      camera.updateProjectionMatrix()
      
      renderer.setSize(clientWidth, clientHeight)
    }
    
    // 退出登录
    const handleLogout = () => {
      emit('logout')
    }
    
    // 保存视图
    const saveView = () => {
      const viewData = {
        cameraPosition: camera.position.toArray(),
        targetPosition: controls.target.toArray(),
        timeSpeed: timeSpeed.value,
        showOrbits: showOrbits.value,
        showLabels: showLabels.value,
        showMoons: showMoons.value,
        realScale: realScale.value,
        timestamp: new Date().toISOString()
      }
      
      console.log('保存视图:', viewData)
      alert('视图已保存')
    }
    
    // 导出数据
    const exportData = () => {
      const exportData = {
        timestamp: new Date().toISOString(),
        solarSystemState: {
          planets: Object.entries(objects.planets).map(([key, planet]) => ({
            id: key,
            name: planet.data.name,
            position: planet.mesh.position.toArray(),
            orbitAngle: planet.orbitAngle
          })),
          moons: Object.entries(objects.moons).map(([key, moon]) => ({
            id: key,
            name: moon.moonData.name,
            orbitAngle: moon.orbitAngle
          }))
        }
      }
      
      const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `solar_system_data_${Date.now()}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
    
    // 监听各种状态变化
    watch(showOrbits, (show) => {
      // 更新轨道显示
      scene.children.forEach(child => {
        if (child.geometry && child.geometry.type === 'RingGeometry' && child !== objects.sun) {
          child.visible = show
        }
      })
    })
    
    watch(showLabels, (show) => {
      Object.values(objects.labels).forEach(label => {
        label.visible = show
      })
    })
    
    watch(showMoons, (show) => {
      // 更新卫星显示
      Object.values(objects.moons).forEach(moon => {
        moon.visible = show
        // 隐藏或显示卫星标签
        if (moon.children && moon.children.length > 0) {
          moon.children.forEach(child => {
            if (child.children && child.children[0] && child.children[0].isText) {
              child.visible = show && showLabels.value
            }
          })
        }
      })
    })
    
    watch(showMoonOrbits, (show) => {
      // 更新卫星轨道显示
      Object.values(objects.moons).forEach(moon => {
        moon.parent.children.forEach(child => {
          if (child.geometry && child.geometry.type === 'RingGeometry') {
            child.visible = show
          }
        })
      })
    })
    
    watch(realScale, () => {
      // 重新创建太阳系以应用新的比例
      if (scene) {
        // 清理现有对象
        while (scene.children.length > 0) {
          const object = scene.children[0]
          scene.remove(object)
          
          // 释放几何体和材质
          if (object.geometry) object.geometry.dispose()
          if (object.material) {
            if (Array.isArray(object.material)) {
              object.material.forEach(m => m.dispose())
            } else {
              object.material.dispose()
            }
          }
        }
        
        // 重置对象引用
        objects.sun = null
        objects.planets = {}
        objects.moons = {}
        objects.orbits = {}
        objects.labels = {}
        
        // 重新创建星空和太阳系
        createStarfield()
        createSun()
        createPlanets()
      }
    })
    
    // 组件挂载时初始化
    onMounted(() => {
      initScene()
      // 默认选中太阳信息
      selectedObject.value = planetaryData.sun
    })
    
    // 组件卸载时清理
    onUnmounted(() => {
      if (animationId) {
        cancelAnimationFrame(animationId)
      }
      
      if (controls) {
        controls.dispose()
      }
      
      if (renderer) {
        renderer.dispose()
        if (containerRef.value && renderer.domElement) {
          containerRef.value.removeChild(renderer.domElement)
        }
      }
      
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      containerRef,
      timeSpeed,
      showOrbits,
      showLabels,
      showMoons,
      realScale,
      showRings,
      showDetailedMoons,
      showMoonOrbits,
      targetObject,
      selectedObject,
      selectedMoon,
      currentUser,
      focusObject,
      pauseSimulation,
      resumeSimulation,
      resetTime,
      zoomIn,
      zoomOut,
      resetView,
      saveView,
      exportData,
      handleLogout
    }
  }
}
</script>

<style scoped>
.solar-dashboard {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #000;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 100;
}

.logo h1 {
  font-size: 24px;
  margin: 0;
  color: #4a9eff;
}

.logo p {
  margin: 5px 0 0 0;
  font-size: 14px;
  color: #aaa;
}

.user-controls {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #4a9eff;
  color: white;
}

.btn-primary:hover {
  background-color: #3588e8;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
}

.btn-secondary:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.btn-danger {
  background-color: #ff4a4a;
  color: white;
}

.btn-danger:hover {
  background-color: #e83535;
}

.dashboard-content {
  flex: 1;
  display: flex;
  position: relative;
}

.planet-system-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.advanced-controls {
  position: absolute;
  top: 100px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  z-index: 50;
}

.control-panel {
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 15px;
  min-width: 220px;
}

.control-panel h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #4a9eff;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 10px;
}

.control-group {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.control-group:last-child {
  margin-bottom: 0;
}

.control-group label {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  white-space: nowrap;
  font-size: 14px;
}

.control-group input[type="range"] {
  flex: 1;
  min-width: 100px;
  cursor: pointer;
}

.control-group input[type="checkbox"] {
  cursor: pointer;
  width: 16px;
  height: 16px;
}

.control-group select {
  width: 100%;
  padding: 5px;
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
}

.control-group select option {
  background-color: #222;
  color: white;
}

.control-group span {
  min-width: 35px;
  text-align: center;
  color: #aaa;
  font-size: 12px;
}

.control-group .btn {
  flex: 1;
  min-width: 60px;
}

.info-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  width: 300px;
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 20px;
  z-index: 50;
}

.info-panel h3 {
  margin: 0 0 15px 0;
  font-size: 20px;
  color: #4a9eff;
  text-align: center;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.info-item .label {
  color: #aaa;
}

.info-item .value {
  color: #fff;
  font-weight: 500;
}

.moon-info {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.moon-info h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #8ab4f8;
}

.moon-info p {
  margin: 5px 0;
  font-size: 13px;
  color: #bbb;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .advanced-controls {
    flex-direction: row;
    flex-wrap: wrap;
    top: 100px;
    right: 10px;
    left: 10px;
    justify-content: center;
  }
  
  .control-panel {
    min-width: calc(50% - 10px);
    max-width: 300px;
  }
  
  .info-panel {
    width: calc(100% - 40px);
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 10px;
    padding: 15px;
  }
  
  .logo h1 {
    font-size: 20px;
  }
  
  .user-controls {
    width: 100%;
    justify-content: center;
  }
  
  .advanced-controls {
    top: 120px;
  }
  
  .control-panel {
    min-width: 100%;
    max-width: none;
  }
}
</style>